package com.share.auth.service;

import cn.hutool.core.util.ObjectUtil;
import com.share.common.core.constant.Constants;
import com.share.common.core.constant.SecurityConstants;
import com.share.common.core.domain.R;
import com.share.common.core.exception.ServiceException;
import com.share.common.core.utils.StringUtils;
import com.share.user.api.RemoteUserInfoService;
import com.share.user.api.model.LoginUserInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zt181
 * @date 2025/7/1
 * 小程序登录服务
 */
@Component
@Slf4j
public class UserLoginService {

    @Autowired
    private RemoteUserInfoService remoteUserInfoService;

    public LoginUserInfo login(String code) {

        // 校验openId
        if (StringUtils.isNull(code)) {
            log.error("微信OpenID为空！");
            throw new ServiceException("微信OpenID为空！");
        }

        // 根据code远程调用查询用户信息
        R<LoginUserInfo> userInfo = remoteUserInfoService.getUserInfoByCode(code, SecurityConstants.INNER);

        if (Constants.SUCCESS != userInfo.getCode() || ObjectUtil.isNull(userInfo.getData())) {
            log.error("查询用户失败: {}", userInfo.getMsg());
            throw new ServiceException("查询用户失败");
        }

        return userInfo.getData();
    }
}
